package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"
	// 导入生成的proto包
	pb "trpc-polaris-demo/proto"
	_ "trpc.group/trpc-go/trpc-filter/debuglog" // 可选：调试日志
	trpc "trpc.group/trpc-go/trpc-go"
	_ "trpc.group/trpc-go/trpc-naming-polarismesh" // 关键：命名中心插件

	"github.com/gorilla/mux"
	thttp "trpc.group/trpc-go/trpc-go/http"
)

// HelloServiceImpl 实现HelloService接口
type HelloServiceImpl struct {
	pb.UnimplementedHelloService
}

// SayHello 实现SayHello方法
func (s *HelloServiceImpl) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloResponse, error) {
	log.Printf("Received SayHello request: name=%s, message=%s", req.Name, req.Message)

	// 模拟一些业务逻辑
	response := &pb.HelloResponse{
		Reply:     fmt.Sprintf("Hello %s! Your message: %s", req.Name, req.Message),
		Timestamp: time.Now().Unix(),
	}

	log.Printf("Sending response: %s", response.Reply)
	return response, nil
}

// GetUserInfo 实现GetUserInfo方法
func (s *HelloServiceImpl) GetUserInfo(ctx context.Context, req *pb.UserRequest) (*pb.UserResponse, error) {
	log.Printf("Received GetUserInfo request: user_id=%d", req.UserId)

	// 模拟用户数据查询
	var response *pb.UserResponse

	switch req.UserId {
	case 1:
		response = &pb.UserResponse{
			UserId:   1,
			Username: "张三",
			Email:    "zhangsan@example.com",
		}
	case 2:
		response = &pb.UserResponse{
			UserId:   2,
			Username: "李四",
			Email:    "lisi@example.com",
		}
	default:
		response = &pb.UserResponse{
			UserId:   req.UserId,
			Username: "未知用户",
			Email:    "unknown@example.com",
		}
	}

	log.Printf("Sending user info: %+v", response)
	return response, nil
}

func handle(w http.ResponseWriter, r *http.Request) {
	// 1. 获取URL参数
	vars := mux.Vars(r)
	userID := vars["user_id"] // 假设路径是/test/{user_id}

	// 2. 处理请求
	log.Printf("Received request for user_id: %s", userID)

	// 3. 返回响应
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]string{
		"status":  "success",
		"user_id": userID,
	})
}

func main() {
	// 创建服务实例
	s := trpc.NewServer()

	// 路由注册
	router := mux.NewRouter()

	// 处理标准 HTTP 请求
	router.HandleFunc("/user/{user_id}", handle).Methods("GET")

	// 注册到 http 服务
	thttp.RegisterNoProtocolServiceMux(s.Service("hello.HelloService"), router)

	// 注册 TRPC 服务
	pb.RegisterHelloServiceService(s, &HelloServiceImpl{})

	log.Println("Starting tRPC server...")

	// 启动服务
	if err := s.Serve(); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}
